package com.lc.luzhengtang.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.activity.ClassficationDetailActivity;
import com.lc.luzhengtang.activity.LoginActivity;
import com.lc.luzhengtang.activity.MarqueueWebActivity;
import com.lc.luzhengtang.activity.NoticeActivity;
import com.lc.luzhengtang.activity.ShopDetailActivity;
import com.lc.luzhengtang.adapter.ClassficationAdapter;
import com.lc.luzhengtang.adapter.IndexAdapter;
import com.lc.luzhengtang.banner.BannerLayout;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.IndexBean;
import com.lc.luzhengtang.conn.Conn;
import com.lc.luzhengtang.conn.ConnAddShop;
import com.lc.luzhengtang.conn.ConnIndex;
import com.lc.luzhengtang.conn.ConnIndexShopList;
import com.lc.luzhengtang.conn.ConnSign;
import com.lc.luzhengtang.glide.GlideImageLoader;
import com.lc.luzhengtang.layoutmanager.FullyGridLayoutManager;
import com.lc.luzhengtang.marqueue.MarqueeView;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.view.GlideCircleTransform;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class SimpleCardFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    @BindView(R.id.img_adv)
    ImageView imgAdv;
    String img_Adv;
    String goods_id;
    @BindView(R.id.img_second)
    ImageView imgSecond;
    String img_second;
    String img_second_id;
    @BindView(R.id.img_third)
    ImageView imgThird;
    @BindView(R.id.img_fourth)
    ImageView imgFourth;
    String fourth_type;
    String fourth;
    /*    @BindView(R.id.refreshLayout)*/
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.layout_mokuai)
    LinearLayout layoutMokuai;
    @BindView(R.id.layout_materal)
    LinearLayout layoutMateral;
    @BindView(R.id.layout_adv)
    LinearLayout layoutAdv;
    private String mTitle;
    @BindView(R.id.banner2)
    BannerLayout banner2;
    Unbinder unbinder;

    @BindView(R.id.text_qiandao)
    TextView textQiandao;
    @BindView(R.id.layout_qiandao)
    LinearLayout layoutQiandao;
    @BindView(R.id.layout_notice)
    LinearLayout layoutNotice;
    @BindView(R.id.layout_fenxiao)
    LinearLayout layoutFenxiao;
    @BindView(R.id.layout_other)
    LinearLayout layoutOther;
    @BindView(R.id.imageView3)
    ImageView imageView3;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
 /*   @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;*/

    List<ConnIndexShopList.Info.NewListContent> mDatas;

    IndexAdapter mIndexAdapter;
    List<String> urls = new ArrayList<>();

    List<IndexBean.DataBean.BannerBean> bannerBeen;

    List<IndexBean.DataBean.BannerBean> goodstypeBeen;
    List<IndexBean.DataBean.InfoBean> infoBeen;
    String notice_id;
    String notice_title;
    ClassficationAdapter newsAdapter;
    private int currentPage = 1;
    protected LayoutInflater inflater;


    private String goodstype_id;
    List<ConnIndexShopList.Info.NewListContent> results;


    List<IndexBean.DataBean.AdvBean> advBeanList = new ArrayList<>();
    String img_first, img_third, img_fourth;

    String types;
    String web_url;

    String sign;
    String fourth_title;

    public static SimpleCardFragment getInstance(String title) {
        SimpleCardFragment sf = new SimpleCardFragment();
        sf.mTitle = title;
        return sf;
    }

    String banner_type;
    String uid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        View v = inflater.inflate(R.layout.fr_simple_card, null);

        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.refreshLayout);


        card_title_tv.setText(mTitle);

        unbinder = ButterKnife.bind(this, v);
        bannerBeen = new ArrayList<>();
        goodstypeBeen = new ArrayList<>();
        infoBeen = new ArrayList<>();
        mDatas = new ArrayList<>();
        results = new ArrayList<>();
        goodstype_id = mTitle;

        return v;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(mTitle)) {
        } else if (mTitle.equals("0")) {
            layoutMokuai.setVisibility(View.VISIBLE);
            layoutMateral.setVisibility(View.VISIBLE);
            layoutAdv.setVisibility(View.VISIBLE);
            imgFourth.setVisibility(View.VISIBLE);
        } else {
            layoutMokuai.setVisibility(View.GONE);
            layoutMateral.setVisibility(View.GONE);
            layoutAdv.setVisibility(View.GONE);
            imgFourth.setVisibility(View.GONE);
        }


        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
            uid = "0";
        } else {
            uid = BaseApplication.basePreferences.readUid();
        }
        initData();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.text_qiandao, R.id.layout_qiandao, R.id.layout_notice, R.id.layout_fenxiao, R.id.layout_other, R.id.imageView3, R.id.marqueeView, R.id.img_adv, R.id.img_second, R.id.img_third, R.id.img_fourth})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_qiandao:
                break;
            case R.id.layout_qiandao:
                if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else if (sign.equals("1")) {
                    textQiandao.setText("今日已签到");
                    LovelyToast.makeText(getActivity(), "今天已签到", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);

                } else {

                    getSignInfo();
                }


                break;
            case R.id.layout_notice:
                Intent intent = new Intent();

                intent.putExtra("id", notice_id);
                intent.putExtra("title", notice_title);
                intent.putExtra("url", "http://luzhengtang.cn/index.php/api/index/service?web_id=1");
                intent.putExtra("flag", "1");
                intent.setClass(getActivity(), NoticeActivity.class);
                startActivity(intent);

                break;
            case R.id.layout_fenxiao:
                Intent intent2 = new Intent();

                intent2.putExtra("id", notice_id);
                intent2.putExtra("title", notice_title);
                intent2.putExtra("url", "http://luzhengtang.cn/index.php/api/index/service?web_id=2");
                intent2.putExtra("flag", "2");
                intent2.setClass(getActivity(), NoticeActivity.class);
                startActivity(intent2);
                break;
            case R.id.layout_other:
                Intent intent3 = new Intent();
                intent3.putExtra("id", notice_id);
                intent3.putExtra("title", notice_title);
                intent3.putExtra("url", "http://luzhengtang.cn/index.php/api/index/service?web_id=3");
                intent3.putExtra("flag", "3");
                intent3.setClass(getActivity(), NoticeActivity.class);
                startActivity(intent3);
                break;
            case R.id.imageView3:
                break;
            case R.id.marqueeView:
                break;


            case R.id.img_adv:
                Intent intent1 = new Intent();
                if (img_Adv.equals("0")) {
                    intent1.putExtra("goods_id", goods_id);

                    intent1.setClass(getActivity(), ShopDetailActivity.class);

                    startActivity(intent1);
                }

                break;

            case R.id.img_second:
                Intent intent5 = new Intent();
                intent5.putExtra("goodstype_id", img_second_id);
                intent5.setClass(getActivity(), ClassficationDetailActivity.class);
                startActivity(intent5);
               /* if (img_second.equals("2")) {
                    intent5.putExtra("goodstype_id", img_second_id);
                    intent5.setClass(getActivity(), ClassficationDetailActivity.class);
                    startActivity(intent5);
                }*/

                break;

            case R.id.img_third:
                Intent intent6 = new Intent();
                intent6.putExtra("url", "http://luzhengtang.cn/index.php/api/index/advweb?adv_id=");
                intent6.putExtra("title", img_third);

                intent6.setClass(getActivity(), IndexWebActivity2.class);
                startActivity(intent6);
                break;
            case R.id.img_fourth:

                Intent intent7 = new Intent();
                intent7.putExtra("url", web_url);
                intent7.putExtra("title", fourth_title);

                intent7.setClass(getActivity(), IndexWebActivity2.class);
                startActivity(intent7);

                break;

        }
    }

    List<String> empty = new ArrayList<>();

    public void getBannerData() {
        Log.d(mTitle, "3333333333333333");
        Log.d(mTitle, "3333333333333333");
        Log.d(mTitle, "3333333333333333");
        empty.add("https://git.oschina.net/yuanchong121/LuZhengTang/blob/master/app/src/main/res/mipmap-hdpi/zhanwei.png");
        new ConnIndex(BaseApplication.basePreferences.readUid(), mTitle, new AsyCallBack<IndexBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, final IndexBean indexBean) throws Exception {
                super.onSuccess(toast, type, o, indexBean);
                if (indexBean != null) {
                    sign = indexBean.getData().getSign();
                    if (indexBean.getData().getSign().equals("1")) {
//                        sign
                        textQiandao.setText("今日已签到");
                    } else {
                        textQiandao.setText("今日未签到");
                    }

                    bannerBeen.clear();
                    bannerBeen = indexBean.getData().getBanner();
                    goodstypeBeen.clear();
                    urls.clear();
                    for (int i = 0; i < bannerBeen.size(); i++) {
                        urls.add(Conn.HOST3 + bannerBeen.get(i).getPicurl());
                    }


                    banner2.setImageLoader(new GlideImageLoader());
                    if (urls.isEmpty()) {
                        banner2.setViewUrls(empty);
                    } else {
                        banner2.setViewUrls(urls);
                    }

                    banner2.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            if (bannerBeen.isEmpty()) {
//                                NSArray * arr = self.homeDataModel.data.banner;
//                                HomeDataModelData_banner * model = arr[index];
//                                if ([model.type isEqualToString:@"1"]) { //1商品列表
//                                    ClassifyDetailViewController *class = [[ClassifyDetailViewController alloc]init];
//                                    NSNumber *num = [NSNumber numberWithInteger:[model.goodstype_id integerValue]];
//                                    class.idNum = num;
//                                    class.hidesBottomBarWhenPushed = YES;
//                                    [[self viewController].navigationController pushViewController:class animated:YES];
//                                }else if ([model.type isEqualToString:@"2"]){//2web页面
//                                    AnnouncementWebViewController *an = [[AnnouncementWebViewController alloc]init];
//                                    an.judgeString = @"1";
//                                    an.banner_idStr = model.id;
//                                    an.title_Str = model.title;
//                                    an.hidesBottomBarWhenPushed = YES;
//                                    [[self viewController].navigationController pushViewController:an animated:YES];
//                                }else if ([model.type isEqualToString:@"3"]){//3外链
//                                    OthersWebViewController *others = [[OthersWebViewController alloc]init];
//                                    others.webStr = model.weburl;
//                                    others.titleStrig = model.title;
//                                    others.hidesBottomBarWhenPushed = YES;
//                                    [[self viewController].navigationController pushViewController:others animated:YES];
//                                }else{
//                                    ProductDetailsViewController *product = [[ProductDetailsViewController alloc]init];
//                                    NSNumber *num = [NSNumber numberWithInteger:[model.goods_id integerValue]];//String转Number
//                                    product.good_idNum = num;
//                                    product.hidesBottomBarWhenPushed = YES;
//                                    [[self viewController].navigationController pushViewController:product animated:YES];
//
//                                }
//                            }

                            } else {
                                banner_type = bannerBeen.get(position).getType() + "";
                                if (banner_type.equals("2")) {
                                    Intent intent = new Intent();
                                    intent.putExtra("url", "http://luzhengtang.cn/index.php/api/index/bannerweb?banner_id=" + bannerBeen.get(position).getId());
                                    intent.putExtra("title", bannerBeen.get(position).getTitle());
                                    intent.setClass(getActivity(), IndexWebActivity2.class);
                                    startActivity(intent);
                                } else if (banner_type.equals("1")) {
                                    Intent intent = new Intent();
                                    intent.putExtra("goodstype_id", bannerBeen.get(position).getGoodstype_id() + "");
                                    intent.putExtra("title", bannerBeen.get(position).getTitle());
                                    intent.setClass(getActivity(), ClassficationDetailActivity.class);
                                    startActivity(intent);
                                }
                            }


                        }
                    });
                    List<String> info = new ArrayList<>();
                    for (int i = 0; i < indexBean.getData().getInfo().size(); i++) {
                        info.add(indexBean.getData().getInfo().get(i).getTitle());
                    }

                    goodstypeBeen = indexBean.getData().getBanner();

                    infoBeen = indexBean.getData().getInfo();

                    for (int i = 0; i < infoBeen.size(); i++) {
                        notice_id = infoBeen.get(i).getId() + "";
                        notice_title = infoBeen.get(i).getTitle();
                    }

                    marqueeView.startWithList(info);
                    marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position, TextView textView) {
                            // position = position + 1;
                            //Toast.makeText(getActivity(), "点击了" + position + "购物车", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.putExtra("url", "http://luzhengtang.cn/index.php/api/index/infos?id=" + infoBeen.get(position).getId() + "");
                            intent.putExtra("title", infoBeen.get(position).getTitle());
                            intent.setClass(getActivity(), MarqueueWebActivity.class);

                            startActivity(intent);
                        }
                    });


                    Glide.with(getActivity())
                            .load(Conn.HOST3 + indexBean.getData().getAdv().get(0).getPicurl())
                            .transform(new GlideCircleTransform(getActivity()))
                            .error(R.mipmap.zhanwei)
                            .placeholder(R.mipmap.zhanwei)
                            .into(imgAdv);
                    img_Adv = indexBean.getData().getAdv().get(0).getType() + "";
                    goods_id = indexBean.getData().getAdv().get(0).getGoods_id() + "";

                    Glide.with(getActivity())
                            .load(Conn.HOST3 + indexBean.getData().getAdv().get(1).getPicurl())
                            .error(R.mipmap.zhanwei)
                            .transform(new GlideCircleTransform(getActivity()))
                            .into(imgSecond);
                    img_second = indexBean.getData().getAdv().get(1).getType() + "";
                    img_second_id = indexBean.getData().getAdv().get(1).getGoodstype_id() + "";
                    Glide.with(getActivity())
                            .load(Conn.HOST3 + indexBean.getData().getAdv().get(2).getPicurl())
                            .error(R.mipmap.zhanwei)
                            .transform(new GlideCircleTransform(getActivity()))
                            .into(imgThird);

                    img_third = indexBean.getData().getAdv().get(2).getTitle();
                    Glide.with(getActivity())
                            .load(Conn.HOST3 + indexBean.getData().getAdv().get(3).getPicurl())
                            .error(R.mipmap.zhanwei)
                            .transform(new GlideCircleTransform(getActivity(), 2))
                            .into(imgFourth);

                    fourth_type = indexBean.getData().getAdv().get(3).getType() + "";
                    fourth_title = indexBean.getData().getAdv().get(3).getTitle();

                    advBeanList = indexBean.getData().getAdv();
                    for (int i = 0; i < advBeanList.size(); i++) {
                        types = advBeanList.get(i).getType() + "";
                        img_first = advBeanList.get(i).getGoodstype_id() + "";
                        web_url = advBeanList.get(i).getWeburl();
                    }


                }


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }
        }


        ).execute(getActivity(), false);
    }


    protected void initData() {
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2));

        mIndexAdapter = new IndexAdapter(null);
        mIndexAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        mIndexAdapter.isFirstOnly(false);
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.line_divider);
//        recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity(), drawable, 2));
        recyclerView.setAdapter(mIndexAdapter);
        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        mIndexAdapter.setOnLoadMoreListener(this);
        //开启loading,获取数据
        setRefreshing(true);
        onRefresh();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
//        initData();

    }

    @Override
    public void onRefresh() {
        currentPage = 1;

        empty.clear();
        new ConnIndexShopList(uid, currentPage, goodstype_id, new AsyCallBack<ConnIndexShopList.Info>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
//                showLoading();
                mIndexAdapter.setEnableLoadMore(false);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, final ConnIndexShopList.Info info) throws Exception {
                results = info.data;
                // results.addAll(info.data);
                if (results != null) {
                    currentPage = 1;
                    mIndexAdapter.setNewData(results);
                }
                if (!bannerBeen.isEmpty()) {
                    bannerBeen.clear();
                }

                recyclerView.setNestedScrollingEnabled(false);


            }


            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                dismissLoading();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                mIndexAdapter.removeAllFooterView();
                //最后调用结束刷新的方法
                setRefreshing(false);
                dismissLoading();
                mIndexAdapter.setEnableLoadMore(true);
            }
        }
        ).execute(getActivity(), false);
        getBannerData();
    }

    String price;

    @Override
    public void onLoadMoreRequested() {
        new ConnIndexShopList(uid, currentPage, goodstype_id, new AsyCallBack<ConnIndexShopList.Info>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                //    showLoading();
                mIndexAdapter.setEnableLoadMore(true);

            }

            @Override
            public void onSuccess(String toast, int type, Object o, final ConnIndexShopList.Info info) throws Exception {

                results = info.data;
                // results.addAll(info.data);

                if (results != null && results.size() > 0) {
                    currentPage++;
                    mIndexAdapter.setNewData(results);
                } else {
                    //显示没有更多数据
                    // newsAdapter.loadComplete();
                    newsAdapter.loadMoreComplete();
                    View noDataView = getActivity().getLayoutInflater().inflate(R.layout.item_no_data, (ViewGroup) recyclerView.getParent(), false);
                    newsAdapter.addFooterView(noDataView);
                }
                recyclerView.setNestedScrollingEnabled(false);
                mIndexAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                        //   Toast.makeText(getActivity(), "点击了" + position, Toast.LENGTH_SHORT).show();
                        price = results.get(position).sales;
                        new ConnAddShop(info.data.get(position).id + "", BaseApplication.basePreferences.readUid(), "1", "盒", price, new AsyCallBack<CommenBean>() {
                            @Override
                            public void onStart(int type) throws Exception {
                                super.onStart(type);
                            }

                            @Override
                            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                                super.onSuccess(toast, type, o, commenBean);
                                //  Toast.makeText(getActivity(), "成功加入购物车", Toast.LENGTH_SHORT).show();
                                LovelyToast.makeText(getActivity(), "成功加入购物车", 0, LovelyToast
                                        .SUCCESS, LovelyToast.SCALE);
                            }

                            @Override
                            public void onFail(String toast, int type) throws Exception {
                                super.onFail(toast, type);
                            }

                            @Override
                            public void onEnd(String toast, int type) throws Exception {
                                super.onEnd(toast, type);
                                //可能需要移除之前添加的布局
                                newsAdapter.removeAllFooterView();
                                //最后调用结束刷新的方法
                                setRefreshing(false);
                            }
                        }

                        ).execute(getActivity(), false);


                    }
                });
            }


            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                dismissLoading();
                LovelyToast.makeText(getActivity(), "请求失败!", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

                mIndexAdapter.removeAllFooterView();
                //最后调用结束刷新的方法
                setRefreshing(false);
                mIndexAdapter.setEnableLoadMore(false);
            }
        }
        ).execute(getActivity(), false);
    }


    //签到
    public void getSignInfo() {

        new ConnSign(BaseApplication.basePreferences.readUid(), new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {

                LovelyToast.makeText(getActivity(), commenBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
//                BaseApplication.basePreferences.saveSign("1");
                textQiandao.setText("今日已签到");

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }


        ).execute(getActivity(), false);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}